from rest_framework import serializers

from apps.users.models import User


class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model=User
        fields="__all__"
        extra_kwargs={
            'password':{
                'write_only': True
            }
        }

    def create(self, validated_data):
        # 调用父类方法创建管理员用户
        admin = super().create(validated_data)
        # 将密码加密
        password = validated_data['password']
        admin.set_password(password)
        admin.is_staff = True
        admin.save()
        return admin

    def update(self, instance, validated_data):
        super().update(instance, validated_data)
        password = validated_data.get('password')
        if password is not None:
            instance.set_password(password)
            instance.save()
        return instance